<?php
/**
 * PhpStorm
 * User: zucheng
 * Date: 2019/3/21
 */

namespace App\Traits;


use App\Library\R;

trait File
{
    /**
     * 允许上传的文件类型 图片+文件
     * @var array
     */
    public $allowExt = [
        "png", "jpg", "jpeg", "gif", "bmp",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml",
    ];

    /**
     * 通过buf格式上传文件
     * @param $content
     * @param string $ext
     * @return mixed
     */
    public function uploadByBuf($content, $ext = 'png')
    {
        try {
            if (!in_array($ext, $this->allowExt)) {
                return R::error('暂不支持此类文件');
            }
            $disk = \Storage::disk(); // 使用默认存储

            $filename = $this->buildFilename($ext);
            $ret = $disk->put($filename, $content);
            if ($ret) {
                return R::success('success', [], $disk->url($filename));
            }

            return R::error('未知异常');
        } catch (\Exception $e) {
            return R::error($e->getMessage());
        }
    }

    /**
     * 生成上传后的文件名
     * @param string $ext
     * @return string
     */
    public function buildFilename($ext = '')
    {
        $filename = date("/Ymd/Hi/") . uniqid() . mt_rand(100000, 999999);
        if (!empty($ext)) {
            $filename = $filename . '.' . $ext;
        }
        return $filename;
    }
}